#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>
#include <string>


using namespace std;

__thread int gval = 10; 

class threadData
{
public:
    threadData(const string& name) 
        :_threadname(name)
    {}

public:
    string _threadname;
};

void* threadRountine(void* arg)
{
    pthread_detach(pthread_self()); //detach thread from main thread,但是不能保证主线程最后退出！
    threadData* td = static_cast<threadData*>(arg);
    int i = 0;
    while (i < 5)
    {
        cout << td->_threadname << "   gval = " << gval << "   &gval = " << &gval << endl;
        i++;    
        sleep(1);
    }

    delete td;
    return nullptr;
}

int main()
{
    vector<pthread_t> tids;
    for (int i = 0; i < 5; i++)
    {
        pthread_t tid;
        threadData* td = new threadData("Thread" + to_string(i));
        pthread_create(&tid, nullptr, threadRountine, td);
        tids.push_back(tid);
        sleep(1);
    }

    return 0;
}